package com.snc.controller.system;


import com.snc.annotation.SystemLog;
import com.snc.controller.index.BaseController;
import com.snc.entity.UserFormMap;
import com.snc.entity.UserRoleFormMap;
import com.snc.exception.SystemException;
import com.snc.plugin.PageView;
import com.snc.util.Common;
import com.snc.util.PasswordHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author lanyuan 2015-11-19
 * @Email: mmm333zzz520@163.com
 * @version 4.0v
 */
@Controller
@RequestMapping("/user/")
public class UserController extends BaseController {
	
	@RequestMapping("listUI")
	public String listUI(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/system/user/list";
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage( String pageNow,
			String pageSize) throws Exception {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		userFormMap=toFormMap(userFormMap, pageNow, pageSize);
        pageView.setRecords(UserFormMap.mapper().findUserPage(userFormMap));//不调用默认分页,调用自已的mapper中findUserPage
        return pageView;
	}

	@RequestMapping("addUI")
	public String addUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/add";
	}

	@ResponseBody
	@RequestMapping("addEntity")
	@SystemLog(module="系统管理",methods="用户管理-新增用户")//凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String addEntity(String txtRoleSelect){
		try {
			UserFormMap userFormMap = getFormMap(UserFormMap.class);
			userFormMap.put("txtRoleSelect", txtRoleSelect);
			PasswordHelper passwordHelper = new PasswordHelper();
//			userFormMap.put("password","123456789");
			passwordHelper.encryptPassword(userFormMap);
			userFormMap.save();
			if (!Common.isEmpty(txtRoleSelect)) {
				String[] txt = txtRoleSelect.split(",");
				List<UserRoleFormMap> ulis = new ArrayList<UserRoleFormMap>();
				UserRoleFormMap userRoleFormMap = null;
				for (String roleId : txt) {
					userRoleFormMap = new UserRoleFormMap();
					userRoleFormMap.put("userId", userFormMap.get("id"));
					userRoleFormMap.put("roleId", roleId);
					ulis.add(userRoleFormMap);
				}
				userRoleFormMap.batchSave(ulis);
			}
		} catch (Exception e) {
			//try catch 必须抛出自定义异常,否则事务失效!   #### lanyuan ####
			String results = "{\"results\":\"error\",\"message\":\""+e+"\"}";
			throw new SystemException(results);
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("deleteEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理-删除用户")//凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity(String ids) throws Exception {
		new UserFormMap().deleteByAttribute("id", ids);
		return "success";
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		if(Common.isNotEmpty(id)){
			model.addAttribute("user", new UserFormMap().findById(id));
		}
		return Common.BACKGROUND_PATH + "/system/user/edit";
	}

	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理-修改用户")//凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity(String txtRoleSelect) throws Exception {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		userFormMap.put("txtRoleSelect", txtRoleSelect);
		userFormMap.update();
		new UserRoleFormMap().deleteByAttribute("userId", userFormMap.get("id"));
		if(!Common.isEmpty(txtRoleSelect)){
			String[] txt = txtRoleSelect.split(",");
			UserRoleFormMap userRoleFormMap = null;
			for (String roleId : txt) {
				userRoleFormMap = new UserRoleFormMap();
				userRoleFormMap.put("userId", userFormMap.get("id"));
				userRoleFormMap.put("roleId", roleId);
				userRoleFormMap.save();
			}
		}
		return "success";
	}
	/**
	 * 验证账号是否存在
	 * 
	 * @author lanyuan Email：mmm333zzz520@163.com date：2015-2-19
	 * @param name
	 * @return
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist(String name) {
		UserFormMap account = new UserFormMap();
		account.put("accountName", name);
		account=account.findbyFrist();
		if (account == null) {
			return true;
		} else {
			return false;
		}
	}
	
	@RequestMapping("seletUser")
	public String seletRole(Model model) throws Exception {
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		List<UserFormMap> list = UserFormMap.mapper().seletUser(userFormMap);
		String ugid = "";
		for (UserFormMap ml : list) {
			ugid += ml.get("id")+",";
		}
		ugid = Common.trimComma(ugid);
		model.addAttribute("txtUserSelect", ugid);
		model.addAttribute("userSelect", list);
		if(StringUtils.isNotBlank(ugid)){
			String[] g = ugid.split(",");
			String v = "";
			for (String s : g) {
				v+="'"+s+"',";
			}
			userFormMap.put("where", " id not in ("+Common.trimComma(v)+")");
		}
		List<UserFormMap> users = userFormMap.findByWhere();
		model.addAttribute("users", users);
		return Common.BACKGROUND_PATH + "/system/user/userSelect";
	}
	@RequestMapping("updateState")
	@ResponseBody
	@Transactional//需要事务操作必须加入此注解
	public String updateState() throws Exception {
		UserFormMap usersFormMap = getFormMap(UserFormMap.class);
		usersFormMap.update();
		return "success";
	}
	
	//密码修改
	@RequestMapping("updatePassword")
	public String updatePassword(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/updatePassword";
	}
	
	//保存新密码
	@RequestMapping("editPassword")
	@ResponseBody
	@Transactional//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理-修改密码")//凡需要处理业务逻辑的.都需要记录操作日志
	public Map<String, Object> editPassword() throws Exception{
		// 当验证都通过后，把用户信息放在session里
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getPrincipal().toString(), userFormMap.getStr("oldpassword"));
		Map<String, Object> map = new HashMap<String, Object>(); 
		try {
			user.login(token);
			userFormMap.put("id", Common.findUserSessionId());
			userFormMap.put("accountName", user.getPrincipal());
			userFormMap.put("password", userFormMap.get("newpassword"));
			//这里对修改的密码进行加密
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(userFormMap);
			userFormMap.update();
			map.put("results", "success");
			map.put("messages", "密码修改成功!");
		} catch (LockedAccountException lae) {
			token.clear();
			map.put("results", "error");
			map.put("messages", "用户已经被锁定不能登录，请与管理员联系！");
		}  catch (AuthenticationException e) {
			token.clear();
			map.put("results", "error");
			map.put("messages", "用户或密码不正确！！");
		}
		return map;
	}
}